import React, { useState } from 'react'
import NavBar from '@/components/NavBar'
import styles from './index.module.scss'
import Input from '@/components/Input'
import { useFormik } from 'formik'
import * as Yup from 'yup'
import classNames from 'classnames'
import { sendCode, login } from '@/store/actions/login'
import { useDispatch } from 'react-redux'
import { Toast } from 'antd-mobile'
import { useHistory, useLocation } from 'react-router'
export default function Login() {
  const dispatch = useDispatch()
  const history = useHistory()
  const location = useLocation()
  // 倒计时
  const [time, setTime] = useState(0)
  // 点击获取验证码
  const onExtraClick = async () => {
    if (time > 0) {
      return
    }
    // 首先对手机号进行验证
    if (!/^1[1-9]\d{9}$/.test(mobile)) {
      formik.setTouched({
        mobile: true,
      })
      return
    }
    // 获取验证码
    await dispatch(sendCode(mobile))
    Toast.success('获取验证码成功')
    // 开启倒计时
    setTime(60)
    let timerId = setInterval(() => {
      setTime((time) => {
        if (time === 1) {
          clearInterval(timerId)
        }
        return time - 1
      })
    }, 1000)
  }

  // Formik 表单对象
  const formik = useFormik({
    // 设置表单字段的初始值
    initialValues: {
      mobile: '13911189111',
      code: '246810',
    },
    // 提交登录
    onSubmit: async (values) => {
      // console.log(values)
      await dispatch(login(values))
      Toast.success('登陆成功', 1)
      console.log(location)
      if (location.state) {
        history.replace(location.state.from)
      } else {
        // 跳转到首页
        history.replace('/home')
      }
    },

    validationSchema: Yup.object({
      mobile: Yup.string()
        .required('手机号不能为空')
        .matches(/^1[1-9]\d{9}$/, '手机号格式错误'),
      code: Yup.string()
        .required('验证码不能为空')
        .matches(/^\d{6}$/, '验证码格式错误'),
    }),
  })

  const {
    values: { mobile, code },
    handleChange,
    handleSubmit,
    handleBlur,
    errors,
    touched,
    isValid,
  } = formik

  // validate(values){
  //   const errors={}
  //   if(!values.mobile){
  //     errors.mobile='手机号不能为空'
  //   }
  //   if(!values.code){
  //     errors.code
  //   }
  // }

  return (
    <div className={styles.root}>
      <NavBar>登录</NavBar>
      <div className="content">
        {/* 标题 */}
        <h3>短信登录</h3>
        <form onSubmit={handleSubmit}>
          {/* 手机号输入框 */}
          <div className="input-item">
            <div className="input-box">
              <Input
                name="mobile"
                placeholder="请输入手机号"
                value={mobile}
                autoComplete="off"
                onBlur={handleBlur}
                onChange={handleChange}
                maxLength={11}
              ></Input>
            </div>
            {touched.mobile && errors.mobile ? (
              <div className="validate">{errors.mobile}</div>
            ) : null}
          </div>

          {/* 短信验证码输入框 */}
          <div className="input-item">
            <div className="input-box">
              <Input
                name="code"
                placeholder="请输入验证码"
                extra={!time ? '发送验证码' : time + 's后获取'}
                onExtraClick={onExtraClick}
                value={code}
                autoComplete="off"
                onChange={handleChange}
                onBlur={handleBlur}
                maxLength={6}
              ></Input>
            </div>
            {touched.code && errors.code ? (
              <div className="validate">{errors.code}</div>
            ) : null}
          </div>

          {/* 登录按钮 */}
          <button
            type="submit"
            className={classNames('login-btn', { disabled: !isValid })}
            disabled={!isValid}
          >
            登录
          </button>
        </form>
      </div>
    </div>
  )
}
